
package com.cnvp.paladin.controller;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import com.cnvp.paladin.core.BaseController;
import com.cnvp.paladin.interceptor.Global;
import com.cnvp.paladin.kit.ConfigKit;
import com.cnvp.paladin.kit.StringKit;
import com.cnvp.paladin.model.Devicecontrol;
import com.cnvp.paladin.model.Equipment;
import com.cnvp.paladin.model.SysUser;
import com.cnvp.paladin.model.SysUserRole;
import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.aop.ClearLayer;
import com.jfinal.kit.EncryptionKit;

@ClearInterceptor(ClearLayer.ALL)
public class WeixinController extends BaseController {
	String OPENID = null ;
	String url = "http://nbzhuoxin.ddns.net/WeChat/WeChatApiServlet?method=send_template";
	
    public Map<String, Object> putjson(Object status_code, Object data, Object status) {
        Map<String, Object> json = new HashMap<String, Object>();
        json.put("code", status_code);
        json.put("data", data);
        json.put("msg", status);
        return json;

    }

    public SysUser findUser(String param){
    	String openid = param;
    	SysUser user = SysUser.dao.where("openid = '"+openid+"'").get(0);
		return user;
    	
    }
    
    public static String doPostRequst(String urlStr, String param) throws IOException {
        URL url = new URL(urlStr);  
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
        conn.setDoInput(true);  
        conn.setDoOutput(true);  
        conn.setRequestMethod("POST"); 
        conn.setRequestProperty("Content-Type",
                "application/json");
        DataOutputStream out = new DataOutputStream(
                conn.getOutputStream());
        out.write(param.getBytes());  
        out.flush();  
        out.close();  
        
		// Read the response from server
		String sCurrentLine = "";
		String sTotalString = "";
		InputStream l_urlStream = conn.getInputStream();
		// Write back the page info 
		BufferedReader l_reader = new BufferedReader(new InputStreamReader(
				l_urlStream));
		while ((sCurrentLine = l_reader.readLine()) != null) {
			sTotalString += sCurrentLine + "\r\n";

		}
		System.out.println("[***Wechat***]Return message : " + sTotalString);
		return sTotalString;
    }
    
    @Before(Global.class)
    public void index() {
    		String  para = getPara("openid");
    		SysUser user = SysUser.dao.where("openid = '"+para+"'").get(0);
    		int userID = user.getInt("id");
            String sql = "where user_id =" + userID;
            setAttr("page", Equipment.dao.paginate(getParaToInt(0, 1), 100, sql));
        }
    @Before(Global.class)
    public void Auth(){		
    	if(isPost()){
    		String openid = getPara("openid"); 
        	Subject subject = SecurityUtils.getSubject();
    		UsernamePasswordToken token = new UsernamePasswordToken(getPara("account"),
    				EncryptionKit.md5Encrypt(getPara("password")));      	        	
        	try {
    			// 4、登录，即身份验证
    			subject.login(token);
    			if(openid != null){
    				SysUser user = SysUser.dao.where("account = '"+getPara("account")+"'").get(0);
    				String user_openid = user.getStr("openid");
    				if(user_openid==null){
    					user.set("openid", openid);
            			user.update();
            			renderJS("alert('绑定成功');WeixinJSBridge.call('closeWindow');");
    				} else if(user_openid !=null && user_openid.equals(openid)){
    					renderJS("alert('已绑定该账号');WeixinJSBridge.call('closeWindow');");
    				} else { 
    					user.set("openid", openid);
    					user.update();
    					renderJS("alert('该账号曾绑定其他微信号，已更改为当前账号');WeixinJSBridge.call('closeWindow');");
   					
    				}
        			
    			} else {
    				renderJS("alert('绑定失败');window.close();");
    			}    			   			
    		} catch (AuthenticationException e) {
    			// 5、身份验证失败
    			alertAndGoback("用户名或密码错误，请重新输入");
    		}
    	}else{
    		OPENID = getPara("openid");
    		setAttr("openid", OPENID);
    		render("auth.html");
    	}    	    	    	    	
    }
             
    public void getStatus(){
    	String logic_id = getPara("logic_id");
    	Equipment eq = Equipment.dao.where("logic_id = '"+logic_id+"'").get(0); 	
    	String status = eq.getStr("status");
    	if(status!=null)
    		renderJson(putjson("0", status, "success"));
    	 else 
    		renderJson(putjson("301", "", "failed"));   	   	
    }
    
    @Before(Global.class)
    public void control(){
    	String logic_id = getPara("logic_id");
    	String action = getPara("action");
    	Equipment eq = Equipment.dao.where("logic_id = '"+logic_id+"'").get(0); 	
    	String status = eq.getStr("status");
    	int user_id = eq.getInt("user_id");
    	String sql = "where user_id =" + user_id;
    	if(status!=null&&status.equals(action)){           	 
            	 setAttr("page", Equipment.dao.paginate(getParaToInt(0, 1), 100,sql));
            	 render("index.html");
    	} else {
    		Devicecontrol dc = getModel(Devicecontrol.class,"devicecontrol");
        	dc.set("id", logic_id);
        	dc.set("command_type", "execute");
        	dc.set("action", action);
        	if(action.equals("open"))
        		dc.set("value", 100);
        	else
        		dc.set("value", 0);
        	if(dc.save()){
        		eq.set("status", action);
        		eq.update();
                	 setAttr("page", Equipment.dao.paginate(getParaToInt(0, 1), 100,sql));
                	 render("index.html");
        	}   		
        	else
        		renderJson(putjson("301", "", "failed"));
    	}
    }
    
}
